<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
 * SugarCRM is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004-2010 SugarCRM Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 *
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 ********************************************************************************/




require_once('include/Dashlets/DashletGeneric.php');


class BirthdayDashlet extends DashletGeneric {

   function BirthdayDashlet($id, $def = null) {
        global $current_user, $app_strings;
		require('custom/modules/Contacts/Dashlets/BirthdayDashlet/BirthdayDashlet.data.php');

        parent::DashletGeneric($id, $def);

        if(empty($def['title'])) $this->title = translate('LBL_BIRTHDAY_DASHLET', 'Contacts');

        $this->searchFields = $dashletData['BirthdayDashlet']['searchFields'];
        $this->columns = $dashletData['BirthdayDashlet']['columns'];

        $this->seedBean = new Contact();
    }
	
	// As the default buildWhere function of the Dashlet class doesn't have the
	// qualified functions to do the math, we just override the method so we can
	// add our own code.
    function buildWhere() {
        global $current_user;
		
        $returnArray = array();

        if(!is_array($this->filters)) {
            // use defaults
            $this->filters = array();
            foreach($this->searchFields as $name => $params) {
                if(!empty($params['default']))
                    $this->filters[$name] = $params['default'];
            }
        }
        foreach($this->filters as $name=>$params) {
            if(!empty($params)) {
                if($name == 'assigned_user_id' && $this->myItemsOnly) continue; // don't handle assigned user filter if filtering my items only
                $widgetDef = $this->seedBean->field_defs[$name];

                $widgetClass = $this->layoutManager->getClassFromWidgetDef($widgetDef, true);
                $widgetDef['table'] = $this->seedBean->table_name;
                $widgetDef['table_alias'] = $this->seedBean->table_name;
				if(!empty($widgetDef['source']) && $widgetDef['source'] == 'custom_fields'){
                    $widgetDef['table'] = $this->seedBean->table_name."_cstm";
                    $widgetDef['table_alias'] = $widgetDef['table'];
                }
                switch($widgetDef['type']) {// handle different types
                    case 'date':
						
						if ($name == 'birthdate') {
							//This must be our birthdate, let's create our own sql where:
							
							//DATEDIFF(STR_TO_DATE(DATE_FORMAT(a.date_entered, "2010-%m-%d"), "%Y-%m-%d"), NOW()) < 10
							
							$GLOBALS['log']->info("Building sql where clause");
	
							// Get the proper field name for the DB type used
							if ($GLOBALS['db']->dbType == 'oci8') {
								$field_name = $widgetDef['table_alias'].".".$name;
							}elseif($GLOBALS['db']->dbType == 'mssql'){
								if (isset ($widgetDef['rel_field'])) {
									$field_name = "(".$widgetDef['table_alias'].".".$name." + ' ' + ".$name.")";
								} else {
									$field_name = $widgetDef['table_alias'].".".$name;
								}
							} else {
								if (isset ($widgetDef['rel_field'])) {
									$field_name = "CONCAT(".$widgetDef['table_alias'].".".$name.",' ',".$name.")";
								} else {
									$field_name = $widgetDef['table_alias'].".".$name;
								}
							}
							$year = date('Y');
							// Determine the specified period:
							switch ($params['type']) {
								case 'TP_today':
									$sqlwhere = "DATEDIFF(STR_TO_DATE(DATE_FORMAT(".$field_name.", '".$year."-%m-%d'), '%Y-%m-%d'), NOW()) = 0\n";
									break;
								case 'TP_yesterday':
									$sqlwhere = "DATEDIFF(STR_TO_DATE(DATE_FORMAT(".$field_name.", '".$year."-%m-%d'), '%Y-%m-%d'), NOW()) = -1\n";
									break;
								case 'TP_tomorrow':
									$sqlwhere = "DATEDIFF(STR_TO_DATE(DATE_FORMAT(".$field_name.", '".$year."-%m-%d'), '%Y-%m-%d'), NOW()) = 1\n";
									break;
								case 'TP_this_month':
									$sqlwhere = "DATE_FORMAT(".$field_name.", '%m') = DATE_FORMAT(NOW(), '%m')\n";
									break;
								case 'TP_last_30_days':
									$sqlwhere = "DATEDIFF(STR_TO_DATE(DATE_FORMAT(".$field_name.", '".$year."-%m-%d'), '%Y-%m-%d'), NOW()) > -31\n";
									array_push($returnArray, $sqlwhere);
									$sqlwhere = "DATEDIFF(STR_TO_DATE(DATE_FORMAT(".$field_name.", '".$year."-%m-%d'), '%Y-%m-%d'), NOW()) <= 0\n";
									break;
								case 'TP_last_7_days':
									$sqlwhere = "DATEDIFF(STR_TO_DATE(DATE_FORMAT(".$field_name.", '".$year."-%m-%d'), '%Y-%m-%d'), NOW()) > -7\n";
									array_push($returnArray, $sqlwhere);
									$sqlwhere = "DATEDIFF(STR_TO_DATE(DATE_FORMAT(".$field_name.", '".$year."-%m-%d'), '%Y-%m-%d'), NOW()) <= 0\n";
									break;
								case 'TP_last_month':
									$sqlwhere = "DATE_FORMAT(".$field_name.", '%m') = DATE_FORMAT(DATE_ADD(NOW(), INTERVAL -1 MONTH), '%m')\n";
									break;
								case 'TP_next_30_days':
									$sqlwhere = "DATEDIFF(STR_TO_DATE(DATE_FORMAT(".$field_name.", '".$year."-%m-%d'), '%Y-%m-%d'), NOW()) >= 0\n";
									array_push($returnArray, $sqlwhere);
									$sqlwhere = "DATEDIFF(STR_TO_DATE(DATE_FORMAT(".$field_name.", '".$year."-%m-%d'), '%Y-%m-%d'), NOW()) < 31\n";
									break;
								case 'TP_next_month':
									$sqlwhere = "DATE_FORMAT(".$field_name.", '%m') = DATE_FORMAT(DATE_ADD(NOW(), INTERVAL 1 MONTH), '%m')\n";
									break;
								case 'TP_this_year': // Not going to show that lists
								case 'TP_next_year': // Show next 7 days instead
								case 'TP_last_year':
								case 'TP_next_7_days':
									$sqlwhere = "DATEDIFF(STR_TO_DATE(DATE_FORMAT(".$field_name.", '".$year."-%m-%d'), '%Y-%m-%d'), NOW()) >= 0\n";
									array_push($returnArray, $sqlwhere);
									$sqlwhere = "DATEDIFF(STR_TO_DATE(DATE_FORMAT(".$field_name.", '".$year."-%m-%d'), '%Y-%m-%d'), NOW()) <= 7\n";
									break;
							}
							$GLOBALS['log']->info("We have a field name");
							//$sqlwhere = "DATEDIFF(STR_TO_DATE(DATE_FORMAT(".$field_name.", '".$year."-%m-%d'), '%Y-%m-%d'), NOW()) < 10\n";
							$GLOBALS['log']->info($sqlwhere);
							array_push($returnArray, $sqlwhere);
						}
						break;
                    case 'datetime':
                        if(is_array($params) && !empty($params)) {
                            if(!empty($params['date']))
                                $widgetDef['input_name0'] = $params['date'];
                            $filter = 'queryFilter' . $params['type'];
						}
                        else {
                            $filter = 'queryFilter' . $params;
                        }
                        array_push($returnArray, $widgetClass->$filter($widgetDef, true));
                        break;
                    case 'assigned_user_name':
                        // This type runs through the SugarWidgetFieldname class, and needs a little extra help to make it through
                        if ( ! isset($widgetDef['column_key']) ) {
                            $widgetDef['column_key'] = $name;
                        }
                        // No break here, we want to run through the default handler
                    default:
                        $widgetDef['input_name0'] = $params;
                        if(is_array($params) && !empty($params)) { // handle array query
                            array_push($returnArray, $widgetClass->queryFilterone_of($widgetDef, false));
                        }
                        else {
                            array_push($returnArray, $widgetClass->queryFilterStarts_With($widgetDef, true));
                        }
                        $widgetDef['input_name0'] = $params;
                    break;
                }
            }
        }

        if($this->myItemsOnly) array_push($returnArray, $this->seedBean->table_name . '.' . "assigned_user_id = '" . $current_user->id . "'");

        return $returnArray;
    }

	
}

?>
